package com.ykq.gateway.back.fliter;

import com.alibaba.fastjson.JSON;
import com.ykq.gateway.back.util.JWTUtil;
import com.ykq.gateway.back.vo.UrlVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @Author: 闫克起
 * @Description:
 * @Date: Create in 11:38 2024/8/7
 */
// 在网关中定义的过滤器--只能在网关中使用。
@Component
public class LoginFilter implements GlobalFilter, Ordered {
    @Autowired
    private UrlVo urlVo;

    @Autowired
    private StringRedisTemplate redisTemplate;


    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        //1. 获取请求路径
        String path = request.getPath().toString();
        //2.判断该路径是否属于放行路径--白名单
        if (urlVo.getWhite().contains(path)) {
            //放行
            return chain.filter(exchange);
        }
        //3. 判断用户是否登录
        String token = request.getHeaders().getFirst("token");
        //4. 校验token是否为空 以及是否合法
        if(StringUtils.hasText(token)&& JWTUtil.verify(token)&&redisTemplate.hasKey("login:"+token)){
            //刷新token过期时间
            redisTemplate.opsForValue().set("login:"+token,"",24, TimeUnit.HOURS);
            //放行
            return chain.filter(exchange);
        }
        //3.2封装返回数据
        Map<String, Object> map = new HashMap<>();
        map.put("msg", "未登录");
        map.put("code", 501);
        //3.3作JSON转换
        byte[] bytes = JSON.toJSONString(map).getBytes(StandardCharsets.UTF_8);
        //3.4调用bufferFactory方法,生成DataBuffer对象
        DataBuffer buffer = response.bufferFactory().wrap(bytes);
        //4.调用Mono中的just方法,返回要写给前端的JSON数据
        return response.writeWith(Mono.just(buffer));
    }

    //优先级 值越小优先级越高
    @Override
    public int getOrder() {
        return 0;
    }
}
